 
  

 






<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<html>

<!-- Mirrored from www.javapractices.com/topic/TopicAction.do;jsessionid=4FCCB481C702D708A7360133D128E359?Id=68 by HTTrack Website Copier/3.x [XR&CO'2010], Sun, 12 Jun 2011 17:27:38 GMT -->
<!-- Added by HTTrack --><meta http-equiv="content-type" content="text/html;charset=UTF-8"><!-- /Added by HTTrack -->
<head>
 <title>
  Java Practices -> Recursive file listing
 </title>
 <link rel="stylesheet" type="text/css" href="../stylesheet8.css" media="all">
 
 <link rel="shortcut icon" href='../images/favicon.ico' type="image/vnd.microsoft.icon">
 <meta name="description" content="Concise presentations of java programming practices, tasks, and conventions, amply illustrated with syntax highlighted code examples.">
 
 <meta name='keywords' content='recursive,java,java programming,java practices,java idiom,java style,java design patterns,java coding conventions,'>
 
 
</head>
 
<body>


<div class='menu-bar'>
 
  <a href='../home/HomeAction.html' title='Table of Contents'>Home</a> |
  <a href='../vote/VoteSummaryAction-2.html' title='View Poll Results'>Poll</a> |
   
  <A href='../feedback/FeedbackAction451f-2.html?Operation=Show' title='Send Your Feedback'>Wiki</a> |
  <b><a href='../source/SourceAction-2.html' title='Grab Source Code'>Source Code</a></b><IMG class='no-margin' SRC="../images/goldstar.gif" ALT=""> |

  <a href='http://www.web4j.com/Java_Web_Application_Framework_Overview.jsp?From=1' title='Free Download - Java Web Application Framework'><b>WEB4J</b></a> |
  
  <a href='http://www.date4j.net/' title='Replacement for java.util.Date'><b>DATE4J</b></a> |

   <a href='../references/ReferencesAction-2.html' title='References'>Links</a>
   
  <form action='http://www.javapractices.com/search/SearchAction.do' method='get' class='search-form'>
   <input type='text' name='SearchTerms' value="" size=12 maxlength=50 class='search'>
   <input type='submit' value="Search">
  </form>
 
</div>

<P>



  

 






<p class="display-messages">

 

 

</p>


<div class="main-layout">
 
   

 




<div class='page-title'>Recursive file listing</div>

<div class='main-body'>
 
<br>The <tt><a href="http://java.sun.com/javase/6/docs/api/java/io/File.html">File</a></tt>
class has methods for listing the contents of a single directory, such
as <tt>list</tt> and <tt>listFiles</tt>, but there is no method for listing
all files in a directory tree.

<p>Here is a simple utility which returns a sorted <tt>List</tt> of <tt>File</tt>
objects which reside under a given root directory. It uses recursion.
<br>
<PRE>

<span class='keyword'>import</span> java.util.*;
<span class='keyword'>import</span> java.io.*;

<span class='comment'>/**
* Recursive file listing under a specified directory.
*  
* @author javapractices.com
* @author Alex Wong
* @author anonymous user
*/</span>
<span class='keyword'>public</span> <span class='keyword'>final</span> <span class='keyword'>class</span> FileListing {

  <span class='comment'>/**
  * Demonstrate use.
  * 
  * @param aArgs - &lt;tt&gt;aArgs[0]&lt;/tt&gt; is the full name of an existing 
  * directory that can be read.
  */</span>
  <span class='keyword'>public</span> <span class='keyword'>static</span> <span class='keyword'>void</span> main(String... aArgs) <span class='keyword'>throws</span> FileNotFoundException {
    File startingDirectory= <span class='keyword'>new</span> File(aArgs[<span class='literal'>0</span>]);
    List&lt;File&gt; files = FileListing.getFileListing(startingDirectory);

    <span class='comment'>//print out all file names, in the the order of File.compareTo()
</span>    <span class='keyword'>for</span>(File file : files ){
      System.out.println(file);
    }
  }
  
  <span class='comment'>/**
  * Recursively walk a directory tree and return a List of all
  * Files found; the List is sorted using File.compareTo().
  *
  * @param aStartingDir is a valid directory, which can be read.
  */</span>
  <span class='keyword'>static</span> <span class='keyword'>public</span> List&lt;File&gt; getFileListing(
    File aStartingDir
  ) <span class='keyword'>throws</span> FileNotFoundException {
    validateDirectory(aStartingDir);
    List&lt;File&gt; result = getFileListingNoSort(aStartingDir);
    Collections.sort(result);
    <span class='keyword'>return</span> result;
  }

  <span class='comment'>// PRIVATE //
</span>  <span class='keyword'>static</span> <span class='keyword'>private</span> List&lt;File&gt; getFileListingNoSort(
    File aStartingDir
  ) <span class='keyword'>throws</span> FileNotFoundException {
    List&lt;File&gt; result = <span class='keyword'>new</span> ArrayList&lt;File&gt;();
    File[] filesAndDirs = aStartingDir.listFiles();
    List&lt;File&gt; filesDirs = Arrays.asList(filesAndDirs);
    <span class='keyword'>for</span>(File file : filesDirs) {
      result.add(file); <span class='comment'>//always add, even if directory
</span>      <span class='keyword'>if</span> ( ! file.isFile() ) {
        <span class='comment'>//must be a directory
</span>        <span class='comment'>//recursive call!
</span>        List&lt;File&gt; deeperList = getFileListingNoSort(file);
        result.addAll(deeperList);
      }
    }
    <span class='keyword'>return</span> result;
  }

  <span class='comment'>/**
  * Directory is valid if it exists, does not represent a file, and can be read.
  */</span>
  <span class='keyword'>static</span> <span class='keyword'>private</span> <span class='keyword'>void</span> validateDirectory (
    File aDirectory
  ) <span class='keyword'>throws</span> FileNotFoundException {
    <span class='keyword'>if</span> (aDirectory == <span class='keyword'>null</span>) {
      <span class='keyword'>throw</span> <span class='keyword'>new</span> IllegalArgumentException(<span class='literal'>"Directory should not be null."</span>);
    }
    <span class='keyword'>if</span> (!aDirectory.exists()) {
      <span class='keyword'>throw</span> <span class='keyword'>new</span> FileNotFoundException(<span class='literal'>"Directory does not exist: "</span> + aDirectory);
    }
    <span class='keyword'>if</span> (!aDirectory.isDirectory()) {
      <span class='keyword'>throw</span> <span class='keyword'>new</span> IllegalArgumentException(<span class='literal'>"Is not a directory: "</span> + aDirectory);
    }
    <span class='keyword'>if</span> (!aDirectory.canRead()) {
      <span class='keyword'>throw</span> <span class='keyword'>new</span> IllegalArgumentException(<span class='literal'>"Directory cannot be read: "</span> + aDirectory);
    }
  }
} 
</PRE>
<br>
<br>Example run :
<p>
<PRE>
>java -cp . FileListing "C:\TEMP\"
C:\TEMP\Hokkaido.txt
C:\TEMP\Honshu.txt
C:\TEMP\mb
C:\TEMP\mb\Kyushu.txt
C:\TEMP\mb\Shikoku.txt
</PRE>
<br>
<br>

</div>





<div class='topic-section'>Would you use this technique?</div>
<div class='main-body'>
  
  <form action="http://www.javapractices.com/vote/AddVoteAction.do" method='post'>
    Yes<input type='radio' name='Choice' value='Y' >
    &nbsp;&nbsp;No<input type='radio' name='Choice' value='N'>
    &nbsp;&nbsp;Undecided<input type='radio' name='Choice' value="?" >
    &nbsp;&nbsp;<input type=submit value="Vote" >
    <input type='hidden' name='Operation' value='Apply'>
    <input type='hidden' name='TopicId' value='68'>
  </form>
</div>

<div style='height:10.0em;'></div>

 
 
</div>

  

 





<div align='center' class='legalese'>  
&copy; 2011 Hirondelle Systems |
<a href='../source/SourceAction-2.html'><b>Source Code</b></a><IMG class='no-margin' SRC="../images/goldstar.gif" ALT=""> |
<a href="mailto:webmaster@javapractices.com">Contact</a> |
<a href="http://creativecommons.org/licenses/by-nc-sa/1.0/">License</a> |
<a href='../apps/cjp.rss'>RSS</a>
<!-- ukey="2AC36CD2" -->
<!-- ckey="16DF3D87" -->
<br>

 Individual code snippets can be used under this <a href='../LICENSE.txt'>BSD license</a> - Last updated on June 6, 2010.<br>
 Over 150,000 unique IPs last month - <span title='Java Practices 2.6.5, Mon May 16 00:00:00 EDT 2011'>Built with</span> <a href='http://www.web4j.com/'>WEB4J</a>.<br>
 - In Memoriam : Bill Dirani -
</div>

<script src="../../www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-2633428-1";
urchinTracker();
</script>



</body>

<!-- Mirrored from www.javapractices.com/topic/TopicAction.do;jsessionid=4FCCB481C702D708A7360133D128E359?Id=68 by HTTrack Website Copier/3.x [XR&CO'2010], Sun, 12 Jun 2011 17:27:38 GMT -->
<!-- Added by HTTrack --><meta http-equiv="content-type" content="text/html;charset=UTF-8"><!-- /Added by HTTrack -->
</html>
